import React, { useState, useEffect } from 'react';
import { Select, Spin } from 'antd';
import debounce from 'lodash/debounce';
import { SelectProps } from 'antd/es/select';
// import type { FormInstance } from 'antd'

export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
  newOpt: ValueType;
}

export default function DebounceSelect<
  ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any
  >({ fetchOptions, debounceTimeout = 800, newOpt, ...props }: DebounceSelectProps) {
  const [fetching, setFetching] = useState(false);
  // const [options, setOptions] = useState<ValueType[]>([]);
  const [options, setOptions] = useState<any[]>([]);
  const fetchRef = React.useRef(0);

  const debounceFetcher = React.useMemo(() => {

    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then(newOptions => {
        const newResult = newOptions.map(item => ({
          label: `${item.buildingAlias}(${item.cityname}-${item.id})`,
          value: item.id,
          key: item.id
        }))
        if (fetchId !== fetchRef.current) {
          return;
        }
        setOptions(newResult);
        setFetching(false);
      });
    };


    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);
  return (
    <Select<ValueType>
      showSearch
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options.length ? options : newOpt}
    />
  );
}